// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const _data = JSON.parse(JSON.stringify(event))
  const _id = _data._id
  delete _data._id
  // 获得当前的 user 数据
  const usersDb = cloud.database().collection('users')
  const userData = await usersDb.where({
    _id
  }).get()
  const user = userData.data[0]
  const { data } = await usersDb.where({
    _id
  }).update({
    data: _data
  })
  // 如果还书了就修改书籍数据库
  const booksDb = cloud.database().collection('books')
  // 如果清空了所有书籍
  if (_data.books.length === 0 && user.books.length > 0) {
     for (let i = 0; i < user.books.length; i++) {
       const bookData = await booksDb.where({
         bookId: user.books[i].bookId
       }).get()
       const book = bookData.data[0]
       delete book._id
       const newOwners = book.owners.filter(item => item !== _id)
       book.owners = newOwners
       book.remain++
       book.status = true
       await booksDb.where({
         bookId: user.books[i].bookId
       }).update({
         data: book
       })
     }
  } else if (user.books.length > _data.books.length) {
    // 如果没清空所有书籍
    const returnBookList = []
    for (let i = 0; i < user.books.length; i++) {
      if (user.books[i].bookId !== _data.books[i-returnBookList.length].bookId) {
        returnBookList.push(user.books[i].bookId)
        const bookData = await booksDb.where({
          bookId: user.books[i].bookId
        }).get()
        const book = bookData.data[0]
        delete book._id
        const newOwners = book.owners.filter(item => item !== _id)
        book.owners = newOwners
        book.remain++
        book.status = true
        await booksDb.where({
          bookId: user.books[i].bookId
        }).update({
          data: book
        })
      }
    }
  }
  return {
    data
  }
}